<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <el-button type="primary" :icon="Plus" @click="AddTrademark"
          >添加</el-button
        >
      </div>
    </template>

    <el-table
      :data="trademarkList"
      v-loading="loading"
      border
      style="width: 100%"
    >
      <el-table-column
        prop="date"
        label="序号"
        type="index"
        align="center"
        width="80"
      />
      <el-table-column prop="tmName" label="品牌名称" width="180" />
      <el-table-column label="品牌Logo">
        <template v-slot="{ row }">
          <img :src="row.logoUrl" alt="" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作">
        <template #default="{ row, $index }">
          <el-button
            size="small"
            type="warning"
            :icon="Edit"
            @click="setTrademarkData(row)"
          />
          <el-button
            size="small"
            type="danger"
            :icon="Delete"
            @click="delTrademarkData(row)"
          />
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9, 12]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout=" prev, pager, next, jumper,->, sizes,total"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog v-model="dialogFormVisible" :title="title">
      <el-form :model="trademark" :rules="rules" ref="ruleFormRef">
        <el-form-item
          label="品牌名称"
          :label-width="formLabelWidth"
          prop="tmName"
        >
          <el-input v-model="trademark.tmName" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="品牌Logo"
          :label-width="formLabelWidth"
          prop="logoUrl"
        >
          <el-upload
            class="avatar-uploader"
            :action="`${BASE_URL}/admin/product/upload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademark.logoUrl"
              :src="trademark.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                仅支持2M大小以内的jpg/png格式文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="CancelSubmit">取消</el-button>
          <el-button type="primary" @click="ConfirmSubmit">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>
<script setup lang="ts">
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import {
  ReqTrademarkList,
  ReqAddTrademarkList,
  ReqDelTrademarkList,
  ReqSetTrademarkList,
  ReqFindOneTrademark,
} from '@/api/product/trademark'
import { ref, onMounted, reactive } from 'vue'
import type { UploadProps, FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import type {
  TrademarkListType,
  TrademarkListRecordsType,
  UpdateTrademarkListType,
} from '@/api/product/model/trademarkModel'
const currentPage = ref<number>(1)
const ruleFormRef = ref<FormInstance>()
const pageSize = ref<number>(5)
const loading = ref<boolean>(true)
const total = ref<number>(10)
const disabled = ref<boolean>(false)
const background = ref<boolean>(false)
const small = ref<boolean>(false)
const trademarkList = ref<TrademarkListRecordsType[]>([])
const BASE_URL = import.meta.env.VITE_API_URL
//切换每页显示数量的事件处理函数
const handleSizeChange = (newPageSize: number) => {
  pageSize.value = newPageSize
  getTrademarkList(currentPage.value, pageSize.value)
}

//切换当前页数的事件处理函数
const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage
  getTrademarkList(currentPage.value, pageSize.value)
}

//发送请求获取品牌管理列表数据的函数
async function getTrademarkList(page: number, limit: number) {
  const result = await ReqTrademarkList(page, limit)
  total.value = result.total
  trademarkList.value = result.records
  loading.value = false
}

//让弹窗表单显示和隐藏的数据
const dialogFormVisible = ref<boolean>(false)

//添加事件处理函数
const AddTrademark = () => {
  ruleFormRef.value?.clearValidate()
  Object.assign(trademark, initTrademark())
  title.value = '添加品牌'
  dialogFormVisible.value = true
}

//添加品牌有关
const title = ref<string>('') //弹窗表单的标题

//图片上传成功的事件处理函数
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  trademark.logoUrl = response.data
}

//图片上传前处理函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // console.log(rawFile.type)
  // console.log(rawFile.size)
  const imgTypes = ['image/jpeg', 'image/jpg', 'image/png']
  if (!imgTypes.includes(rawFile.type)) {
    ElMessage.error('必须上传JPG和PNG格式的图片文件')
    return false
  } else if (rawFile.size > 1024 * 1024 * 2) {
    ElMessage.error('上传的图片文件大小不能超过2MB')
    return false
  }
  ruleFormRef.value?.clearValidate(['logoUrl'])
  return true
}

//取消提交表单的事件处理函数
const CancelSubmit = () => {
  dialogFormVisible.value = false
}

//确认提交表单的事件处理函数
const ConfirmSubmit = async () => {
  let result
  if (trademark.id) {
    result = await ReqSetTrademarkList(trademark)
    trademark.id = undefined
  } else {
    result = await ReqAddTrademarkList(trademark)
  }
  ElMessage.success('操作品牌成功')
  dialogFormVisible.value = false
  getTrademarkList(currentPage.value, pageSize.value)
}

//表单数据
const trademark = reactive<UpdateTrademarkListType>({
  logoUrl: '',
  tmName: '',
})

//删除list的事件处理函数
const delTrademarkData = async (row: any) => {
  ElMessageBox.confirm(`是否删除${row.tmName}这条品牌数据`, '删除品牌', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      await ReqDelTrademarkList(row.id)
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      getTrademarkList(currentPage.value, pageSize.value)
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

//修改list的事件处理函数
const setTrademarkData = async (row: any) => {
  ruleFormRef.value?.clearValidate()
  Object.assign(trademark, initTrademark())
  const result = await ReqFindOneTrademark(row.id)
  Object.assign(trademark, {
    logoUrl: result.logoUrl,
    tmName: result.tmName,
    id: row.id,
  })
  dialogFormVisible.value = true
  title.value = '修改品牌'
}

//表单校验规则
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: '品牌名称不能为空,请输入', trigger: 'blur' },
    {
      min: 1,
      max: 6,
      message: '品牌名称介于1--6个字符之间,请重输',
      trigger: 'blur',
    },
  ],
  logoUrl: [{ required: true, message: '请上传图片', trigger: 'change' }],
})

const formLabelWidth = '140px'

const initTrademark = () => ({ tmName: '', logoUrl: '' })

// const trademark = reactive<TrademarkListType>(initTrademark())
onMounted(() => {
  getTrademarkList(currentPage.value, pageSize.value)
})
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
}
</style>
